package com.rxmvp.rxjavademo;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.rxmvp.rxjavademo.RxBus.Events;
import com.rxmvp.rxjavademo.RxBus.RxBus;
import com.rxmvp.rxjavademo.RxRetrofit.Response.BaseResponse;
import com.rxmvp.rxjavademo.bean.NewsBean;
import com.trello.rxlifecycle.ActivityEvent;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.io.InputStream;

import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class MainActivity extends RxAppCompatActivity{

    private Button btnSource;
    private Button btnNetwork;
    private ProgressBar progressBar;
    private ImageView image;
    private Subscription subscription;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        http://f.hiphotos.baidu.com/image/pic/item/bba1cd11728b47101489df48c0cec3fdfd03238b.jpg
        btnSource = (Button) findViewById(R.id.btn_source);
        btnNetwork = (Button) findViewById(R.id.btn_network);
        progressBar = (ProgressBar) findViewById(R.id.progress);
        progressBar.setVisibility(View.GONE);
        image = (ImageView) findViewById(R.id.image);

        initRxBus();
    }

    private void initRxBus() {
        //接收事件，获取总线传来的图片，并显示到ImageView中
        RxBus.with(this)
                .setEvent(Events.LOAD_IAMGE)
                .setLifecycleEvent(ActivityEvent.DESTROY)
                .onNext(new Action1<Events<?>>() {
                    @Override
                    public void call(Events<?> events) {
                        Log.e("tag", events.toString());
                        image.setImageDrawable((Drawable) events.getContent());
                    }
                })
                .onError(new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e("tag", throwable.getMessage());
                    }
                }).create();
    }

    public void loadSource(View view) {
        Observable.create(new Observable.OnSubscribe<Drawable>() {
            @Override
            public void call(Subscriber<? super Drawable> subscriber) {
                if (!subscriber.isUnsubscribed()) {
                    Drawable drawable = ContextCompat.getDrawable(MainActivity.this, R.drawable.one);
                    subscriber.onNext(drawable);
                    subscriber.onCompleted();
                }
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Drawable>() {
                    @Override
                    public void onCompleted() {
                        progressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(Drawable drawable) {
                        image.setImageDrawable(drawable);
                    }

                    @Override
                    public void onStart() {
                        super.onStart();
                        progressBar.setVisibility(View.VISIBLE);
                    }
                });
    }

    public void loadSourceFromNet(View view) {
        Observable<ResponseBody> observable = App.getService().getBitmap();
        subscription = observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {
                        progressBar.setVisibility(View.GONE);

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("tag", e.getMessage());
                        progressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        InputStream byteStream = responseBody.byteStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(byteStream);
                        image.setImageBitmap(bitmap);
                    }

                    @Override
                    public void onStart() {
                        super.onStart();
                        progressBar.setVisibility(View.VISIBLE);
                    }
                });

    }

    public void toRxBus(View view) {
        startActivity(new Intent(this, RxBusActivity.class));
    }

    public void toNetwork(View view) {
        startActivity(new Intent(this, RxRetrofitActivity.class));
    }

    interface NetService{
        @GET("image/pic/item/bba1cd11728b47101489df48c0cec3fdfd03238b.jpg")
        Observable<ResponseBody> getBitmap();

        //如果是json数据，可以获取经过gson解析后的bean对象
        @GET("toutiao/index")
        Observable<BaseResponse<NewsBean>> getJson1(@Query("type") String type,
                                                    @Query("key") String key);
        //可以直接获取一个ResponseBody对象
        @GET("toutiao/index")
        Observable<ResponseBody> getJson2(@Query("type") String type,
                                          @Query("key") String key);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消订阅，防止内存泄漏
        if (subscription != null && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
    }
}
